﻿using Lr.Templating.FluentMapping;
using System.Linq;

namespace Lr.Templating
{
    /// <summary>
    /// Implementation of <see cref="INonGenericTemplate"/>,
    /// which defines a non generic template.
    /// </summary>
    public class NonGenericTemplate : TemplateBase, INonGenericTemplate
    {
        /// <summary>
        /// Constructs a new <see cref="TemplateBase"/> instance.
        /// </summary>
        /// <param name="templateString"></param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="templateString"/> is null or empty.</exception>
        public NonGenericTemplate(string templateString)
            : base(templateString)
        {
        }

        /// <summary>
        /// Maps a placeholder to a value.
        /// </summary>
        /// <param name="placeholder">The placeholder to be mapped</param>
        /// <exception cref="ArgumentNullExcpetion">When <paramref name="placeholder"/> is null or empty.</exception>
        public INonGenericTemplateMappingBuilder Map(string placeholder)
        {
            ThrowIf.NullOrEmpty(() => placeholder);

            var mappingBuilder = new NonGenericTemplateMappingBuilder(this, placeholder);
            return mappingBuilder;
        }

        /// <summary>
        /// Gets the template with all it's placeholders replaced by the mapped values.
        /// </summary>
        /// <returns>The with all it's placeholders replaced by the mapped values.</returns>
        public string GetProcessedTemplate()
        {
            var processedTemplateString = this.TemplateString;

            foreach (var mapping in this.TemplateMappings.Cast<INonGenericTemplateMapping>())
                processedTemplateString =
                    processedTemplateString.Replace(mapping.Placeholder, mapping.GetValue());

            return processedTemplateString;
        }
    }
}
